package com.cloudkinto.service.order.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.assist.ISqlRunner;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cloudkinto.common.constant.SysConstant;
import com.cloudkinto.common.exception.BizException;
import com.cloudkinto.common.utils.OkHttpUtils;
import com.cloudkinto.common.utils.TimeUtils;
import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;
import com.cloudkinto.dao.ShopDao;
import com.cloudkinto.entity.OrderBigcommerceDo;
import com.cloudkinto.dao.OrderBigcommerceDao;
import com.cloudkinto.entity.ShopDo;
import com.cloudkinto.service.order.OrderBigcommerceProductService;
import com.cloudkinto.service.order.OrderBigcommerceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloudkinto.service.order.OrderBigcommerceShipaddressService;
import com.cloudkinto.service.order.vo.amazon.OrderAmazonExcelReq;
import com.cloudkinto.service.order.vo.amazon.UpdateSysMemoReq;
import com.cloudkinto.service.order.vo.bigcommerce.OrderBigComProductEntity;
import com.cloudkinto.service.order.vo.bigcommerce.OrderBigComShippingAddressEntity;
import com.cloudkinto.service.order.vo.bigcommerce.OrderBigCommerceEntity;
import com.cloudkinto.service.order.vo.shopify.OrderShopifyEntity;
import com.cloudkinto.service.order.vo.shopify.OrderShopifyRes;
import com.cloudkinto.service.orderoutput.vo.OrderOutputAddReq;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author ding
 * @since 2022-11-08
 */
@Service
public class OrderBigcommerceServiceImpl extends ServiceImpl<OrderBigcommerceDao, OrderBigcommerceDo> implements OrderBigcommerceService {

    @Autowired
    private ShopDao shopDao;
    @Autowired
    private OrderBigcommerceDao dao;
    @Autowired
    private OrderBigcommerceShipaddressService shippingAddressService;
    @Autowired
    private OrderBigcommerceProductService productService;

    @Override
    public SingleResult addInit() {
        return null;
    }

    @Override
    public Object add(Object req, Long userId) {
        return null;
    }

    @Override
    public SingleResult updateInit(Long id) {
        return null;
    }

    @Override
    public Object update(Object updateVo, Long userId) {
        return null;
    }

    @Override
    public void sendOut(List<Long> orderOutputIds) {

    }

    @Override
    public int delete(Long id, Long userId) {
        return 0;
    }

    @Override
    public Object detail(Long id) {
        return null;
    }

    @Override
    public SingleResult pageInit(Long userId, Long companyId) {
        return null;
    }

    @Override
    public List<OrderShopifyRes> getList(Map<String, String> map) {
        return null;
    }

    @Override
    public PageResult getListPage(Map<String, String> map) {
        return null;
    }

    @Override
    public SingleResult sync(Long shopId, String startDate, String endDate) {
        ShopDo shopDo = shopDao.selectById(shopId);
        long lastId = 0;
        if (shopDo == null) {
            throw new BizException(SysConstant.Shop_NotExist);
        }
//        int count = getOrderCount(shopDo, startDate, endDate);
        String url = "https://api.bigcommerce.com/stores/" + shopDo.getBigComStoreHash() + "/v2/orders";
        Map<String, String> bodyMap = null;
        List<String> orderFiledIds = new ArrayList<>();
        url = url + "?max_date_modified=" + endDate + "&min_date_modified=" + startDate;
        OkHttpClient.Builder client = OkHttpUtils.getUnsafeOkHttpClient().newBuilder();
        client.connectTimeout(60, TimeUnit.SECONDS).readTimeout(60, TimeUnit.SECONDS).writeTimeout(60, TimeUnit.SECONDS).retryOnConnectionFailure(true);
        Map<String, String> params = new HashMap<>();
        Request request = new Request.Builder()
                .addHeader("Content-Type", "application/json;charset=utf-8")
                .addHeader("Accept", "application/json")
                .addHeader("X-Auth-Token", shopDo.getBigComAccessToken()).url(url).get().build();
        Response response = null;
        String body = "";
        try {
            response = client.build().newCall(request).execute();
            body = response.body().string();
            System.out.println(body);
        } catch (IOException e) {
            e.printStackTrace();
        }
        List<OrderBigCommerceEntity> orderBigcommerceDos = JSON.parseArray(body, OrderBigCommerceEntity.class);
        orderFiledIds.addAll(handlerSyncAfter(orderBigcommerceDos, shopDo));
        String[] stringIds = new String[]{};
        orderFiledIds.toArray(stringIds);
        sendOut(stringIds, 338L, shopDo.getCompanyId(), shopDo.getAutoSendOutFlag());
        return SingleResult.success();
    }

    private List<String> handlerSyncAfter(List<OrderBigCommerceEntity> orderBigcommerceDos, ShopDo shopDo) {
        for (OrderBigCommerceEntity orderBigCommerceEntity : orderBigcommerceDos) {
            OrderBigcommerceDo bigcommerceDo = dao.selectOne(new LambdaQueryWrapper<OrderBigcommerceDo>()
                    .eq(OrderBigcommerceDo::getOrderId, orderBigCommerceEntity.getId())
                    .eq(OrderBigcommerceDo::getShopId, shopDo.getId())
                    .last("limit 1"));
            if (bigcommerceDo == null) {
                BeanUtils.copyProperties(orderBigCommerceEntity, bigcommerceDo);
                bigcommerceDo.setOrderId(orderBigCommerceEntity.getId());
                dao.insert(bigcommerceDo);
            } else {
                long oId = bigcommerceDo.getId();
                bigcommerceDo.setOrderId(orderBigCommerceEntity.getId());
                BeanUtils.copyProperties(orderBigCommerceEntity, bigcommerceDo);
                bigcommerceDo.setOrderId(orderBigCommerceEntity.getId());
                bigcommerceDo.setId(oId);
                dao.updateById(bigcommerceDo);
            }
            String url = orderBigCommerceEntity.getShippingAddresses().getUrl();

          String body= getOkhttpResponse(url,shopDo);
            List<OrderBigComShippingAddressEntity> shippingAddressEntityList = JSON.parseArray(body, OrderBigComShippingAddressEntity.class);
            shippingAddressService.addEntityList(shippingAddressEntityList,orderBigCommerceEntity.getId());
            String urlProduct = orderBigCommerceEntity.getProducts().getUrl();

          String bodyProduct= getOkhttpResponse(urlProduct,shopDo);
            List<OrderBigComProductEntity> productEntities = JSON.parseArray(bodyProduct, OrderBigComProductEntity.class);
            productService.addEntityList(productEntities,orderBigCommerceEntity.getId());
        }
        return null;
    }

    private String getOkhttpResponse(String url,ShopDo shopDo) {
        OkHttpClient.Builder client = OkHttpUtils.getUnsafeOkHttpClient().newBuilder();
        client.connectTimeout(60, TimeUnit.SECONDS).readTimeout(60, TimeUnit.SECONDS).writeTimeout(60, TimeUnit.SECONDS).retryOnConnectionFailure(true);
        Map<String, String> params = new HashMap<>();
        Request request = new Request.Builder()
                .addHeader("Content-Type", "application/json;charset=utf-8")
                .addHeader("Accept", "application/json")
                .addHeader("X-Auth-Token", shopDo.getBigComAccessToken()).url(url).get().build();
        Response response = null;
        String body = "";
        try {
            response = client.build().newCall(request).execute();
            body = response.body().string();
            System.out.println(body);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return body;
    }

    @Override
    public void exportExcel(Map<String, String> map, OrderAmazonExcelReq req, HttpServletResponse response) throws Exception {

    }

    @Override
    public SingleResult markSendOut(List<Long> ids, Long userId) {
        return null;
    }

    @Override
    public SingleResult updateSysMemo(UpdateSysMemoReq req, Long userId, Long companyId) {
        return null;
    }

    @Override
    public SingleResult systemMemoInit(Long id) {
        return null;
    }

    @Override
    public SingleResult sendOut(String[] orderids, Long userId, Long companyId, boolean b) {
        return null;
    }

    @Override
    public SingleResult sendOutNopackage(String orderid, Long userId, Long companyId) {
        return null;
    }

    @Override
    public SingleResult sendOutMatch(List<OrderOutputAddReq> orderOutputAddReqList, Long userId, boolean isAuto) {
        return null;
    }

    @Override
    public SingleResult webhook(String type) {
        return null;
    }

    @Override
    public void autoRefreshOrder() {
        List<ShopDo> shopBeans = shopDao.selectList(null);
        for (ShopDo shop : shopBeans) {
            if (shop.getShopifyHost() != null && shop.getShopifyToken() != null) {
                try {
                    sync(shop.getId(), TimeUtils.getCurrentDateFormat(-3), null);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
